package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.qf.model.Card;
import com.qf.model.Massage;
import com.qf.model.User;
import com.qf.service.BindService;
import com.qf.service.impl.BindServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet("/BindServlet")
public class BindServlet extends BascServlet {
    BindService bindService = new BindServiceImpl();

    public void findBindById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //根据c_id查找到当前登录对象的所有信息
        String c_id = request.getParameter("c_id");
        Card card = bindService.findBindById(c_id);
        Massage<Card> m = null;

        if (card != null) {
            m = new Massage<>(1, "未绑定", card);
        } else {
            m = new Massage<>(-1, "已绑定或账号不正确");
        }
        String s = JSON.toJSONString(m);
        response.getWriter().write(s);
    }

    public void updateBind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //根据c_id修改bind
        String c_id=request.getParameter("c_id");
        String pwd = request.getParameter("pwd");
        String code = request.getParameter("code");
        String phone = request.getParameter("c_phone");

        // 获取 Session 中的验证码
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session 中的验证码
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //通过银行卡号查到这张银行卡所有信息
        Card card = bindService.findBindById(c_id);
        Massage<Card> m = null;
        //判断验证码是否正确
        if (token.equalsIgnoreCase(code)&& token!=null){
            //判断支付密码是否正确
            if (card.getC_pwd().equals(pwd)){
                //执行sql语句
                int bind = bindService.updateBind(c_id);
                if(bind>0){
                    //成功
                    m=new Massage<>(1,"绑卡成功！");
                }else {
                    //绑卡失败
                    m=new Massage<>(1,"绑卡失败！");
                }
            }else {
                //支付密码错误
                m=new Massage<>(1,"支付密码错误！");
            }
        }else {
            //验证码错
            m=new Massage<>(1,"验证码错！");
        }
        String s = JSON.toJSONString(m);
        response.getWriter().write(s);
    }

}
